import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './role.decorator';
import { Role } from './role.enum';
import { AuthService } from 'src/auth/auth.service';

// 权限守卫 => 需要手动调用jwtService检验token： 路由先到权限守卫再到jwt守卫
@Injectable()
export class RoleGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private readonly authService: AuthService,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!requiredRoles) return true;
    const req = context.switchToHttp().getRequest();
    // 获取token，并验证用户信息
    const user = this.authService.verifyToken(
      req.get('Authorization')?.replace('Bearer ', ''),
    );
    console.log('登录用户==============', user);
    return requiredRoles.some((role) => user.roles?.includes(role));
  }
}
